import os
import sys
from PyQt5.QtWidgets import QApplication, QMainWindow, QDesktopWidget, QDialog, QWidget
from PyQt5 import QtGui, QtWidgets, QtCore
import pandas as pd
from P3_main import Ui_P3_main
from about import Ui_Dialog
from help import Ui_help_Form
from image import Ui_image_form
import P3_draw


def center(self):
    screen = QDesktopWidget().screenGeometry()
    size = self.geometry()
    self.move(int((screen.width() - size.width()) / 2), int((screen.height() - size.height()) / 2))


class AboutDialog(QMainWindow, Ui_Dialog):
    def __init__(self):
        super(AboutDialog, self).__init__()
        self.setupUi(self)
        center(self)


class HelpForm(QWidget, Ui_help_Form):
    def __init__(self):
        super(HelpForm, self).__init__()
        self.setupUi(self)
        # path = QFileInfo("./Pearson3 Tools 开发文档.html").absoluteFilePath()
        # print(path)
        # self.help_webView.load(QUrl(path))
        center(self)


class ImageForm(QWidget, Ui_image_form):
    def __init__(self):
        super(ImageForm, self).__init__()
        self.setupUi(self)
        center(self)


class MyMainWidgets(QWidget, Ui_P3_main):
    def __init__(self):
        super(MyMainWidgets, self).__init__()
        self.winabout = AboutDialog()
        self.help_url = HelpForm()
        # self.help_url.setWindowFlags(QtCore.Qt.WindowStaysOnTopHint)
        self.image = ImageForm()
        self.image.setWindowFlags(QtCore.Qt.WindowStaysOnTopHint)
        self.setupUi(self)
        self.dataview_tableWidget.setEditTriggers(QtWidgets.QTableView.NoEditTriggers)
        self.toal_lineEdit.setFocusPolicy(QtCore.Qt.NoFocus)
        self.miss_lineEdit.setFocusPolicy(QtCore.Qt.NoFocus)
        self.mean_lineEdit.setFocusPolicy(QtCore.Qt.NoFocus)
        self.Cs_lineEdit.setFocusPolicy(QtCore.Qt.NoFocus)
        self.Cv_lineEdit.setFocusPolicy(QtCore.Qt.NoFocus)
        center(self)
        self.about_Btn.clicked.connect(self.aboutdialogshow)
        self.openfile_Btn.clicked.connect(self.open_file)
        self.help_Btn.clicked.connect(self.help_urlshow)
        self.N_doubleSpinBox.valueChanged.connect(self.drawimg)
        self.image_Btn.clicked.connect(self.save_image)
        self.data_Btn.clicked.connect(self.save_data)

    def closeEvent(self, a0: QtGui.QCloseEvent) -> None:
        sys.exit(0)

    def create_table(self, total, sum_nan, Ex, Cs, qcv, fp, qpredict_real, Pq, RMSE):
        global data
        self.toal_lineEdit.setText("{:d}".format(total))
        self.miss_lineEdit.setText("{:}".format(sum_nan['col2']))
        self.mean_lineEdit.setText("{:.1f}".format(Ex))
        self.Cs_lineEdit.setText("{:.1f}".format(Cs))
        self.Cv_lineEdit.setText("{:.1f}".format(qcv))
        cols_name = ['离均系数Φ', '设计值xp', '重现期P']
        dict_fp = {'离均系数': fp}
        dict_RMSE = {'绝对均方差': RMSE}
        # print(dict_RMSE)
        dict_qpredict_real = {'设计值xp': qpredict_real}
        dict_Pq = {'重现期': Pq}
        data = pd.concat([pd.DataFrame(dict_fp),
                          pd.DataFrame(dict_qpredict_real), pd.DataFrame(dict_Pq)], axis=1)
        cols = len(data.columns)
        rows = len(data.index)
        self.dataview_tableWidget.setRowCount(rows)
        self.dataview_tableWidget.setColumnCount(cols)
        self.dataview_tableWidget.setHorizontalHeaderLabels(cols_name)
        for col in range(cols):
            for row in range(len(data.iloc[:, col])):
                newItem = QtWidgets.QTableWidgetItem("{:>20.1f}".format(data.iloc[row, col]))
                self.dataview_tableWidget.setItem(row, col, newItem)

        # self.Cs_doubleSpinBox.value(Cs)
        # self.Cv_doubleSpinBox.value(qcv)

    # def open_help(self):
    #     filename, _ = QFileDialog.getOpenFileName(QWidget(), 'open', r"./Pearson3 Tools 开发文档.html")
    #     # file_path = './Pearson3 Tools 开发文档.html'
    #     os.system(filename)

    def open_file(self):
        # filename, filetype = QtWidgets.QFileDialog.getOpenFileName(self, caption="选取文件",
        #                                                            directory=os.getcwd(),
        #                                                            filter="All Files(*);;Text(*.txt);;Excelx("
        #                                                                   "*.xlsx);Excel(*.xls)")
        file_open = QtWidgets.QFileDialog(self, caption="选取文件",
                                          directory=os.getcwd(),
                                          filter="All Files(*);;Text(*.txt);;Excelx(""*.xlsx);Excel(*.xls)")
        file_open.fileSelected.connect(self.drawimg)
        file_open.setAcceptMode(QtWidgets.QFileDialog.AcceptOpen)
        file_open.open()

    def save_image(self):
        save_image, _ = QtWidgets.QFileDialog.getSaveFileName(self, caption="保存图片",
                                                              directory=os.getcwd(),
                                                              filter="All Files(*);;jpeg(*.jpg);;png(""*.png)")
        if save_image != '':
            temp = open(QtCore.QFileInfo(tempimage).absoluteFilePath(), 'rb')
            data = temp.read()
            with open(save_image, 'wb') as f:
                f.write(data)
            temp.close()
        else:
            return

    def save_data(self):
        save_file, _ = QtWidgets.QFileDialog.getSaveFileName(self, caption="保存图片",
                                                             directory=os.getcwd(),
                                                             filter="All Files(*);;txt(*.txt);;\
                                                             csv(*.csv);;xls(*.xls);;xlsx(*.xlsx")
        if save_file != '':
            if save_file[-3:] == 'txt' or save_file[-3:] == 'txt':
                data.round(2).to_csv(save_file, sep='\t')
            elif save_file[-3:] == 'xls' or save_file[-3:] == 'lsx':
                data.round(2).to_excel(save_file)
        else:
            return

    def aboutdialogshow(self):
        # self.winabout.setWindowFlags(QtCore.Qt.WindowStaysOnTopHint)
        self.winabout.show()

    def help_urlshow(self):
        self.help_url.show()

    def imageshow(self, tempimage):
        self.image.show()
        scene = QtWidgets.QGraphicsScene()
        imgShow = QtGui.QImage()
        imgShow.load(tempimage)
        imgShow = imgShow.scaled(self.image.graphicsView.width(), self.image.graphicsView.height())
        scene.addPixmap(QtGui.QPixmap().fromImage(imgShow))
        self.image.graphicsView.setScene(scene)
        self.image.graphicsView.fitInView(QtWidgets.QGraphicsPixmapItem(QtGui.QPixmap(imgShow)))
        # self.image.show()

    def drawimg(self, file_sel):
        global tempimage
        imagename = self.imagename_lineEdit.text()
        N = self.N_doubleSpinBox.value()
        total, sum_nan, Ex, Cs, qcv, fp, qpredict_real, Pq, RMSE, tempimage = P3_draw.draw(file_sel, imagename, N)
        # total, sum_nan, Ex, Cs, qcv, fp, Q, Pq = P3_draw.draw(filename)
        self.create_table(total, sum_nan, Ex, Cs, qcv, fp, qpredict_real, Pq, RMSE)
        self.imageshow(tempimage)

        # 显示图像
        # scene = QGraphicsScene()
        # imgShow = QImage()
        # imgShow.load(saveimage)
        # # imgShow = imgShow.scaled(self.P3_graph.width(), self.P3_graph.height())
        # scene.addPixmap(QPixmap().fromImage(imgShow))
        # self.P3_graph.setScene(scene)


if __name__ == '__main__':
    app = QApplication(sys.argv)
    myWin = MyMainWidgets()
    myWin.show()
    sys.exit(app.exec_())
